﻿using Sys.Core.Sys;
using Sys.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace Sys.Api.Admin
{
    public class ManageApi
    {
        public string Login(HttpSessionState session, string username, string password, string validate)
        {
            JsonMsg result = new JsonMsg();

            if (session["ValidateCode"] != null)
            {
                string code = session["ValidateCode"].ToString();

                if (!validate.ToLower().Equals(code.ToLower()))
                {
                    result.Message = "验证码错误";
                    return JsonHelper.ToJson(result);
                }
            }
            else
            {
                result.Message = "验证码错误";
                return JsonHelper.ToJson(result);
            }

            SysUser model = UserBll.I.Login(username, password);

            if (model != null)
            {
                if (model.IsVisible)
                {
                    FormsAuthentication.SignOut();

                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(model.ID, true);
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                    string userData = "Manage";

                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData, FormsAuthentication.FormsCookiePath);

                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);

                    HttpContext.Current.Response.Cookies.Add(authCookie);

                    result.Success = true;
                }
                else { result.Message = "账号已被禁用!"; }
            }
            else { result.Message = "登录失败,请检查账号密码!"; }

            return JsonHelper.ToJson(result);
        }
    }
}
